<!DOCTYPE html>












  


<html class="theme-next mist use-motion" lang="zh-CN">
<head><meta name="generator" content="Hexo 3.8.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
































<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=6.6.0" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=6.6.0">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/avatar.jpg?v=6.6.0">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/avatar.jpg?v=6.6.0">


  <link rel="mask-icon" href="/images/logo.svg?v=6.6.0" color="#222">









<script id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Mist',
    version: '6.6.0',
    sidebar: {"position":"left","display":"hide","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: false,
    fastclick: false,
    lazyload: false,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>


  




  <meta name="description" content="涉猎广泛，不亦乐乎，不求甚解。">
<meta property="og:type" content="website">
<meta property="og:title" content="isunimp">
<meta property="og:url" content="http://yoursite.com/index.html">
<meta property="og:site_name" content="isunimp">
<meta property="og:description" content="涉猎广泛，不亦乐乎，不求甚解。">
<meta property="og:locale" content="zh-CN">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="isunimp">
<meta name="twitter:description" content="涉猎广泛，不亦乐乎，不求甚解。">






  <link rel="canonical" href="http://yoursite.com/">



<script id="page.configurations">
  CONFIG.page = {
    sidebar: "",
  };
</script>

  <title>isunimp</title>
  












  <noscript>
  <style>
    .use-motion .motion-element,
    .use-motion .brand,
    .use-motion .menu-item,
    .sidebar-inner,
    .use-motion .post-block,
    .use-motion .pagination,
    .use-motion .comments,
    .use-motion .post-header,
    .use-motion .post-body,
    .use-motion .collection-title { opacity: initial; }

    .use-motion .logo,
    .use-motion .site-title,
    .use-motion .site-subtitle {
      opacity: initial;
      top: initial;
    }

    .use-motion .logo-line-before i { left: initial; }
    .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope="" itemtype="http://schema.org/WebPage" lang="zh-CN">

  
  
    
  

  <div class="container sidebar-position-left 
  page-home">
    <div class="headband"></div>

    <header id="header" class="header" itemscope="" itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">isunimp</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
    
      
        <p class="site-subtitle">isunimp</p>
      
    
  </div>

  <div class="site-nav-toggle">
    <button aria-label="切换导航栏">
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>



<nav class="site-nav">
  
    <ul id="menu" class="menu">
      
        
        
        
          
          <li class="menu-item menu-item-home menu-item-active">

    
    
    
      
    

    

    <a href="/" rel="section"><i class="menu-item-icon fa fa-fw fa-home"></i> <br>首页</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-archives">

    
    
    
      
    

    

    <a href="/archives/" rel="section"><i class="menu-item-icon fa fa-fw fa-archive"></i> <br>归档</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-about">

    
    
    
      
    

    

    <a href="/about/" rel="section"><i class="menu-item-icon fa fa-fw fa-user"></i> <br>关于</a>

  </li>

      
      
    </ul>
  

  
    

  

  
</nav>



  



</div>
    </header>

    


    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          
          <div id="content" class="content">
            
  <section id="posts" class="posts-expand">
    
      

  

  
  
  

  

  <article class="post post-type-normal" itemscope="" itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/2019/03/26/HikariCP源码深度解读（二）/">

    <span hidden itemprop="author" itemscope="" itemtype="http://schema.org/Person">
      <meta itemprop="name" content="isunimp">
      <meta itemprop="description" content="涉猎广泛，不亦乐乎，不求甚解。">
      <meta itemprop="image" content="/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope="" itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="isunimp">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
                
                
                <a href="/2019/03/26/HikariCP源码深度解读（二）/" class="post-title-link" itemprop="http://yoursite.com/index.html">HikariCP源码深度解读（二）</a>
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">

            
            
            

            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              

              
                
              

              <time title="创建时间：2019-03-26 16:45:20" itemprop="dateCreated datePublished" datetime="2019-03-26T16:45:20+08:00">2019-03-26</time>
            

            
              

              
                
                <span class="post-meta-divider">|</span>
                

                <span class="post-meta-item-icon">
                  <i class="fa fa-calendar-check-o"></i>
                </span>
                
                  <span class="post-meta-item-text">更新于</span>
                
                <time title="修改时间：2019-04-11 21:50:16" itemprop="dateModified" datetime="2019-04-11T21:50:16+08:00">2019-04-11</time>
              
            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope="" itemtype="http://schema.org/Thing"><a href="/categories/HikariCP/" itemprop="url" rel="index"><span itemprop="name">HikariCP</span></a></span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        
          
            <p><a href="https://isunimp.gitee.io/2019/03/19/HikariCP%E6%BA%90%E7%A0%81%E6%B7%B1%E5%BA%A6%E8%A7%A3%E8%AF%BB%EF%BC%88%E4%B8%80%EF%BC%89/" target="_blank" rel="noopener">上一篇</a>文章中介绍了 Hikari 的并发管理（包含了连接的获取、释放、添加），这篇主要介绍一下 <code>DataSource</code> 等各种 JDBC 接口的实现，以及各个类之间的关系。</p>
<h3 id="HikariDataSource"><a href="#HikariDataSource" class="headerlink" title="HikariDataSource"></a>HikariDataSource</h3><p><a href="https://github.com/brettwooldridge/HikariCP/blob/HikariCP-3.3.1/src/main/java/com/zaxxer/hikari/HikariDataSource.java" target="_blank" rel="noopener">HikariDataSource </a>这个类是 <code>Hikari</code> 直接暴露给用户的类，实现了 <code>DataSource</code> 接口。</p>
<p>老规矩先看几个重要的属性<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 注意继承关系</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">HikariDataSource</span> <span class="keyword">extends</span> <span class="title">HikariConfig</span> <span class="keyword">implements</span> <span class="title">DataSource</span>, <span class="title">Closeable</span></span></span><br><span class="line"><span class="class"></span>&#123;</span><br><span class="line">    <span class="comment">// 原子布尔型变量标记连接池状态</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> AtomicBoolean isShutdown = <span class="keyword">new</span> AtomicBoolean();</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 连接池对象</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> HikariPool fastPathPool;</span><br><span class="line">    <span class="comment">// 连接池对象</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">volatile</span> HikariPool pool;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>为什么有两个连接池对象？</p>
<p>先看看两个构造方法<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 构造器 1</span></span><br><span class="line"><span class="comment">// 未进行任务初始化</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="title">HikariDataSource</span><span class="params">()</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="keyword">super</span>();</span><br><span class="line">    fastPathPool = <span class="keyword">null</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 构造器 2</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="title">HikariDataSource</span><span class="params">(HikariConfig configuration)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="comment">// 校验配置是否有效</span></span><br><span class="line">   configuration.validate();</span><br><span class="line">   <span class="comment">// 值拷贝，HikariDataSource 继承自 HikariConfig</span></span><br><span class="line">   configuration.copyStateTo(<span class="keyword">this</span>);</span><br><span class="line"></span><br><span class="line">   LOGGER.info(<span class="string">"&#123;&#125; - Starting..."</span>, configuration.getPoolName());</span><br><span class="line">   <span class="comment">// 初始化连接池</span></span><br><span class="line">   pool = fastPathPool = <span class="keyword">new</span> HikariPool(<span class="keyword">this</span>);</span><br><span class="line">   LOGGER.info(<span class="string">"&#123;&#125; - Start completed."</span>, configuration.getPoolName());</span><br><span class="line"></span><br><span class="line">   <span class="keyword">this</span>.seal();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>再看 <code>getConnection</code> 方法实现</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> Connection <span class="title">getConnection</span><span class="params">()</span> <span class="keyword">throws</span> SQLException</span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (isClosed()) &#123;</span><br><span class="line">        <span class="keyword">throw</span> <span class="keyword">new</span> SQLException(<span class="string">"HikariDataSource "</span> + <span class="keyword">this</span> + <span class="string">" has been closed."</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">// fastPathPool 不为空，直接使用</span></span><br><span class="line">    <span class="keyword">if</span> (fastPathPool != <span class="keyword">null</span>) &#123;</span><br><span class="line">        <span class="keyword">return</span> fastPathPool.getConnection();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    HikariPool result = pool;</span><br><span class="line">    <span class="keyword">if</span> (result == <span class="keyword">null</span>) &#123;</span><br><span class="line">        <span class="keyword">synchronized</span> (<span class="keyword">this</span>) &#123;</span><br><span class="line">            result = pool;</span><br><span class="line">            <span class="comment">// double check</span></span><br><span class="line">            <span class="keyword">if</span> (result == <span class="keyword">null</span>) &#123;</span><br><span class="line">                validate();</span><br><span class="line">                LOGGER.info(<span class="string">"&#123;&#125; - Starting..."</span>, getPoolName());</span><br><span class="line">                <span class="keyword">try</span> &#123;</span><br><span class="line">                    <span class="comment">// 初始化 pool</span></span><br><span class="line">                    pool = result = <span class="keyword">new</span> HikariPool(<span class="keyword">this</span>);</span><br><span class="line">                    <span class="keyword">this</span>.seal();</span><br><span class="line">                &#125;</span><br><span class="line">                <span class="keyword">catch</span> (PoolInitializationException pie) &#123;</span><br><span class="line">                    <span class="keyword">if</span> (pie.getCause() <span class="keyword">instanceof</span> SQLException) &#123;</span><br><span class="line">                        <span class="keyword">throw</span> (SQLException) pie.getCause();</span><br><span class="line">                    &#125;</span><br><span class="line">                    <span class="keyword">else</span> &#123;</span><br><span class="line">                        <span class="keyword">throw</span> pie;</span><br><span class="line">                    &#125;</span><br><span class="line">                &#125;</span><br><span class="line">                LOGGER.info(<span class="string">"&#123;&#125; - Start completed."</span>, getPoolName());</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> result.getConnection();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>当使用第二个构造器初始化时，会初始化好 fastPathPool，getConnection 方法可以直接使用。<br>当使用第一个构造方法初始化，会等到 getConnection 方法才会去初始化 pool，为了保证线程安全使用 double check的方式，pool 变量还加了 volatile 关键字，效率必然没有第二种初始化的方式高，可能这就是作者为什么声明了两个 pool 的原因吧， 效率高的命名为 fastPathPool。</p>
<h3 id="HikariPool"><a href="#HikariPool" class="headerlink" title="HikariPool"></a>HikariPool</h3><p>HikariDataSource 只是用户接口，真正提供连接池服务的是 <a href="https://github.com/brettwooldridge/HikariCP/blob/86cabf08623a8f9c9ab697a95a277690496b6fae/src/main/java/com/zaxxer/hikari/pool/HikariPool.java" target="_blank" rel="noopener">HikariPool</a>，还是先看属性：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">final</span> <span class="class"><span class="keyword">class</span> <span class="title">HikariPool</span> <span class="keyword">extends</span> <span class="title">PoolBase</span> <span class="keyword">implements</span> <span class="title">HikariPoolMXBean</span>, <span class="title">IBagStateListener</span></span></span><br><span class="line"><span class="class"></span>&#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="keyword">int</span> POOL_NORMAL = <span class="number">0</span>;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="keyword">int</span> POOL_SUSPENDED = <span class="number">1</span>;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="keyword">int</span> POOL_SHUTDOWN = <span class="number">2</span>;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">volatile</span> <span class="keyword">int</span> poolState;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> <span class="keyword">long</span> aliveBypassWindowMs = Long.getLong(<span class="string">"com.zaxxer.hikari.aliveBypassWindowMs"</span>, MILLISECONDS.toMillis(<span class="number">500</span>));</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> <span class="keyword">long</span> housekeepingPeriodMs = Long.getLong(<span class="string">"com.zaxxer.hikari.housekeeping.periodMs"</span>, SECONDS.toMillis(<span class="number">30</span>));</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> String EVICTED_CONNECTION_MESSAGE = <span class="string">"(connection was evicted)"</span>;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> String DEAD_CONNECTION_MESSAGE = <span class="string">"(connection is dead)"</span>;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 创建连接的任务，实现了Callable</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> PoolEntryCreator poolEntryCreator = <span class="keyword">new</span> PoolEntryCreator(<span class="keyword">null</span> <span class="comment">/*logging prefix*/</span>);</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> PoolEntryCreator postFillPoolEntryCreator = <span class="keyword">new</span> PoolEntryCreator(<span class="string">"After adding "</span>);</span><br><span class="line">    <span class="comment">// 任务队列副本</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> Collection&lt;Runnable&gt; addConnectionQueue;</span><br><span class="line">    <span class="comment">// 执行添加任务的线程池</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> ThreadPoolExecutor addConnectionExecutor;</span><br><span class="line">    <span class="comment">// 执行关闭连接的线程池</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> ThreadPoolExecutor closeConnectionExecutor;</span><br><span class="line">    <span class="comment">// 并发管理组件</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> ConcurrentBag&lt;PoolEntry&gt; connectionBag;</span><br><span class="line">    <span class="comment">// 连接泄露检查相关</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> ProxyLeakTaskFactory leakTaskFactory;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> SuspendResumeLock suspendResumeLock;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 定时调度</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> ScheduledExecutorService houseKeepingExecutorService;</span><br><span class="line">    <span class="comment">// 定时任务（关闭空闲的连接）</span></span><br><span class="line">    <span class="keyword">private</span> ScheduledFuture&lt;?&gt; houseKeeperTask;</span><br></pre></td></tr></table></figure>
<p>构造方法大致看一下</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="title">HikariPool</span><span class="params">(<span class="keyword">final</span> HikariConfig config)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="comment">// 主要初始化一些参数</span></span><br><span class="line">    <span class="keyword">super</span>(config);</span><br><span class="line">    <span class="comment">// 并发管理组件，HikariPool实现了 IBagStateListener 接口</span></span><br><span class="line">    <span class="keyword">this</span>.connectionBag = <span class="keyword">new</span> ConcurrentBag&lt;&gt;(<span class="keyword">this</span>);</span><br><span class="line">    <span class="comment">// 这个和 JMX 有关，不管</span></span><br><span class="line">    <span class="keyword">this</span>.suspendResumeLock = config.isAllowPoolSuspension() ? <span class="keyword">new</span> SuspendResumeLock() : SuspendResumeLock.FAUX_LOCK;</span><br><span class="line">    <span class="comment">// 参数化定时调度</span></span><br><span class="line">    <span class="keyword">this</span>.houseKeepingExecutorService = initializeHouseKeepingExecutorService();</span><br><span class="line">    <span class="comment">// 检查数据库配置是否有效</span></span><br><span class="line">    checkFailFast();</span><br><span class="line">    <span class="comment">// 和Metrics有关，先不管</span></span><br><span class="line">    <span class="keyword">if</span> (config.getMetricsTrackerFactory() != <span class="keyword">null</span>) &#123;</span><br><span class="line">        setMetricsTrackerFactory(config.getMetricsTrackerFactory());</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">else</span> &#123;</span><br><span class="line">        setMetricRegistry(config.getMetricRegistry());</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    setHealthCheckRegistry(config.getHealthCheckRegistry());</span><br><span class="line"></span><br><span class="line">    handleMBeans(<span class="keyword">this</span>, <span class="keyword">true</span>);</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 初始化线程池</span></span><br><span class="line">    ThreadFactory threadFactory = config.getThreadFactory();</span><br><span class="line">    LinkedBlockingQueue&lt;Runnable&gt; addQueue = <span class="keyword">new</span> LinkedBlockingQueue&lt;&gt;(config.getMaximumPoolSize());</span><br><span class="line">    <span class="keyword">this</span>.addConnectionQueue = unmodifiableCollection(addQueue);</span><br><span class="line">    <span class="keyword">this</span>.addConnectionExecutor = createThreadPoolExecutor(addQueue, poolName + <span class="string">" connection adder"</span>, threadFactory, <span class="keyword">new</span> ThreadPoolExecutor.DiscardPolicy());</span><br><span class="line">    <span class="keyword">this</span>.closeConnectionExecutor = createThreadPoolExecutor(config.getMaximumPoolSize(), poolName + <span class="string">" connection closer"</span>, threadFactory, <span class="keyword">new</span> ThreadPoolExecutor.CallerRunsPolicy());</span><br><span class="line">    <span class="comment">// </span></span><br><span class="line">    <span class="keyword">this</span>.leakTaskFactory = <span class="keyword">new</span> ProxyLeakTaskFactory(config.getLeakDetectionThreshold(), houseKeepingExecutorService);</span><br><span class="line">    <span class="comment">// 空闲连接监测任务，初始化池的时候已经启动了</span></span><br><span class="line">    <span class="keyword">this</span>.houseKeeperTask = houseKeepingExecutorService.scheduleWithFixedDelay(<span class="keyword">new</span> HouseKeeper(), <span class="number">100L</span>, housekeepingPeriodMs, MILLISECONDS);</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (Boolean.getBoolean(<span class="string">"com.zaxxer.hikari.blockUntilFilled"</span>) &amp;&amp; config.getInitializationFailTimeout() &gt; <span class="number">1</span>) &#123;</span><br><span class="line">        addConnectionExecutor.setCorePoolSize(Runtime.getRuntime().availableProcessors());</span><br><span class="line">        addConnectionExecutor.setMaximumPoolSize(Runtime.getRuntime().availableProcessors());</span><br><span class="line"></span><br><span class="line">        <span class="keyword">final</span> <span class="keyword">long</span> startTime = currentTime();</span><br><span class="line">        <span class="keyword">while</span> (elapsedMillis(startTime) &lt; config.getInitializationFailTimeout() &amp;&amp; getTotalConnections() &lt; config.getMinimumIdle()) &#123;</span><br><span class="line">            quietlySleep(MILLISECONDS.toMillis(<span class="number">100</span>));</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        addConnectionExecutor.setCorePoolSize(<span class="number">1</span>);</span><br><span class="line">        addConnectionExecutor.setMaximumPoolSize(<span class="number">1</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h4 id="获取连接"><a href="#获取连接" class="headerlink" title="获取连接"></a>获取连接</h4><p>还是看最繁琐的 getConnection</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> Connection <span class="title">getConnection</span><span class="params">(<span class="keyword">final</span> <span class="keyword">long</span> hardTimeout)</span> <span class="keyword">throws</span> SQLException</span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="comment">// 不管这个</span></span><br><span class="line">    suspendResumeLock.acquire();</span><br><span class="line">    <span class="keyword">final</span> <span class="keyword">long</span> startTime = currentTime();</span><br><span class="line"></span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">        <span class="keyword">long</span> timeout = hardTimeout;</span><br><span class="line">        <span class="keyword">do</span> &#123;</span><br><span class="line">            <span class="comment">// 从并发管理组件获取</span></span><br><span class="line">            PoolEntry poolEntry = connectionBag.borrow(timeout, MILLISECONDS);</span><br><span class="line">            <span class="keyword">if</span> (poolEntry == <span class="keyword">null</span>) &#123;</span><br><span class="line">                <span class="keyword">break</span>; <span class="comment">// We timed out... break and throw exception</span></span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">            <span class="keyword">final</span> <span class="keyword">long</span> now = currentTime();</span><br><span class="line">            <span class="comment">// 检查有效性</span></span><br><span class="line">            <span class="keyword">if</span> (poolEntry.isMarkedEvicted() || (elapsedMillis(poolEntry.lastAccessed, now) &gt; aliveBypassWindowMs &amp;&amp; !isConnectionAlive(poolEntry.connection))) &#123;</span><br><span class="line">                closeConnection(poolEntry, poolEntry.isMarkedEvicted() ? EVICTED_CONNECTION_MESSAGE : DEAD_CONNECTION_MESSAGE);</span><br><span class="line">                timeout = hardTimeout - elapsedMillis(startTime);</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">else</span> &#123;</span><br><span class="line">                metricsTracker.recordBorrowStats(poolEntry, startTime);</span><br><span class="line">                <span class="comment">// 创建代理连接，返回的类型是 ProxyConnection</span></span><br><span class="line">                <span class="comment">// 同时创建一个定时调度任务，检查连接是否泄漏</span></span><br><span class="line">                <span class="keyword">return</span> poolEntry.createProxyConnection(leakTaskFactory.schedule(poolEntry), now);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125; <span class="keyword">while</span> (timeout &gt; <span class="number">0L</span>);</span><br><span class="line"></span><br><span class="line">        metricsTracker.recordBorrowTimeoutStats(startTime);</span><br><span class="line">        <span class="keyword">throw</span> createTimeoutException(startTime);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">catch</span> (InterruptedException e) &#123;</span><br><span class="line">        Thread.currentThread().interrupt();</span><br><span class="line">        <span class="keyword">throw</span> <span class="keyword">new</span> SQLException(poolName + <span class="string">" - Interrupted during connection acquisition"</span>, e);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">finally</span> &#123;</span><br><span class="line">        suspendResumeLock.release();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h4 id="关闭连接"><a href="#关闭连接" class="headerlink" title="关闭连接"></a>关闭连接</h4><p>我们在使用连接后会调用 <code>close</code> 方法关闭连接，但是在使用连接池的时，不会真的将连接关闭，在获取连接时，Hikari 会创建一个代理返回，所以看一下 <a href="https://github.com/brettwooldridge/HikariCP/blob/86cabf08623a8f9c9ab697a95a277690496b6fae/src/main/java/com/zaxxer/hikari/pool/ProxyConnection.java" target="_blank" rel="noopener">ProxyConnection</a> 的 close 方法</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">final</span> <span class="keyword">void</span> <span class="title">close</span><span class="params">()</span> <span class="keyword">throws</span> SQLException</span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="comment">// 先关闭所有 Statement</span></span><br><span class="line">    closeStatements();</span><br><span class="line">    <span class="comment">// delegate 是 jdbc 的 Connection 对象</span></span><br><span class="line">    <span class="keyword">if</span> (delegate != ClosedConnection.CLOSED_CONNECTION) &#123;</span><br><span class="line">        <span class="comment">// 取消泄漏检查任务</span></span><br><span class="line">        <span class="comment">// 非正常情况，连接长时间没有释放，泄漏检查任务就会被触发</span></span><br><span class="line">        leakTask.cancel();</span><br><span class="line"></span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            <span class="keyword">if</span> (isCommitStateDirty &amp;&amp; !isAutoCommit) &#123;</span><br><span class="line">                delegate.rollback();</span><br><span class="line">                lastAccess = currentTime();</span><br><span class="line">                LOGGER.debug(<span class="string">"&#123;&#125; - Executed rollback on connection &#123;&#125; due to dirty commit state on close()."</span>, poolEntry.getPoolName(), delegate);</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">            <span class="keyword">if</span> (dirtyBits != <span class="number">0</span>) &#123;</span><br><span class="line">                poolEntry.resetConnectionState(<span class="keyword">this</span>, dirtyBits);</span><br><span class="line">                lastAccess = currentTime();</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">            delegate.clearWarnings();</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">catch</span> (SQLException e) &#123;</span><br><span class="line">            <span class="keyword">if</span> (!poolEntry.isMarkedEvicted()) &#123;</span><br><span class="line">                <span class="keyword">throw</span> checkException(e);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">finally</span> &#123;</span><br><span class="line">            delegate = ClosedConnection.CLOSED_CONNECTION;</span><br><span class="line">            <span class="comment">// 释放连接</span></span><br><span class="line">            poolEntry.recycle(lastAccess);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h4 id="添加连接"><a href="#添加连接" class="headerlink" title="添加连接"></a>添加连接</h4><p>HikariPool 实现了 IBagStateListener 接口，当连接不足时，会调用 <code>addBagItem</code> 方法</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">addBagItem</span><span class="params">(<span class="keyword">final</span> <span class="keyword">int</span> waiting)</span></span></span><br><span class="line"><span class="function"></span>&#123;   <span class="comment">// 检查应该添加的数量</span></span><br><span class="line">    <span class="keyword">final</span> <span class="keyword">boolean</span> shouldAdd = waiting - addConnectionQueue.size() &gt;= <span class="number">0</span>;</span><br><span class="line">    <span class="keyword">if</span> (shouldAdd) &#123;</span><br><span class="line">        <span class="comment">// 向线程池提交添加任务</span></span><br><span class="line">        addConnectionExecutor.submit(poolEntryCreator);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>addBagItem 方法比较简单，主要看一下任务的实现</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">private</span> <span class="keyword">final</span> <span class="class"><span class="keyword">class</span> <span class="title">PoolEntryCreator</span> <span class="keyword">implements</span> <span class="title">Callable</span>&lt;<span class="title">Boolean</span>&gt;</span></span><br><span class="line"><span class="class"></span>&#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> String loggingPrefix;</span><br><span class="line"></span><br><span class="line">    PoolEntryCreator(String loggingPrefix)</span><br><span class="line">    &#123;</span><br><span class="line">        <span class="keyword">this</span>.loggingPrefix = loggingPrefix;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Boolean <span class="title">call</span><span class="params">()</span></span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">        <span class="keyword">long</span> sleepBackoff = <span class="number">250L</span>;</span><br><span class="line">        <span class="keyword">while</span> (poolState == POOL_NORMAL &amp;&amp; shouldCreateAnotherConnection()) &#123;</span><br><span class="line">            <span class="comment">// 创建一个连接</span></span><br><span class="line">            <span class="keyword">final</span> PoolEntry poolEntry = createPoolEntry();</span><br><span class="line">            <span class="keyword">if</span> (poolEntry != <span class="keyword">null</span>) &#123;</span><br><span class="line">                <span class="comment">// 添加到并发管理</span></span><br><span class="line">                connectionBag.add(poolEntry);</span><br><span class="line">                logger.debug(<span class="string">"&#123;&#125; - Added connection &#123;&#125;"</span>, poolName, poolEntry.connection);</span><br><span class="line">                <span class="keyword">if</span> (loggingPrefix != <span class="keyword">null</span>) &#123;</span><br><span class="line">                logPoolState(loggingPrefix);</span><br><span class="line">                &#125;</span><br><span class="line">                <span class="keyword">return</span> Boolean.TRUE;</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="comment">// 创建失败了，准备重试</span></span><br><span class="line">            quietlySleep(sleepBackoff);</span><br><span class="line">            sleepBackoff = Math.min(SECONDS.toMillis(<span class="number">10</span>), Math.min(connectionTimeout, (<span class="keyword">long</span>) (sleepBackoff * <span class="number">1.5</span>)));</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> Boolean.FALSE;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">// 同步检查是否过载</span></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">synchronized</span> <span class="keyword">boolean</span> <span class="title">shouldCreateAnotherConnection</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> getTotalConnections() &lt; config.getMaximumPoolSize() &amp;&amp;</span><br><span class="line">            (connectionBag.getWaitingThreadCount() &gt; <span class="number">0</span> || getIdleConnections() &lt; config.getMinimumIdle());</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>还剩下一些零散的代码就不贴了，作者的思路还是挺好的，代码也不复杂，最关键还是上一篇的并发管理，连接泄露处理方式值得借鉴，有兴趣还是把源码下载下来看看。</p>

          
        
      
    </div>

    

    
    
    

    

    
      
    
    

    

    <footer class="post-footer">
      

      

      

      
      
        <div class="post-eof"></div>
      
    </footer>
  </div>
  
  
  
  </article>


    
      

  

  
  
  

  

  <article class="post post-type-normal" itemscope="" itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/2019/03/19/HikariCP源码深度解读（一）/">

    <span hidden itemprop="author" itemscope="" itemtype="http://schema.org/Person">
      <meta itemprop="name" content="isunimp">
      <meta itemprop="description" content="涉猎广泛，不亦乐乎，不求甚解。">
      <meta itemprop="image" content="/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope="" itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="isunimp">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
                
                
                <a href="/2019/03/19/HikariCP源码深度解读（一）/" class="post-title-link" itemprop="http://yoursite.com/index.html">HikariCP源码深度解读（一）</a>
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">

            
            
            

            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              

              
                
              

              <time title="创建时间：2019-03-19 16:45:20" itemprop="dateCreated datePublished" datetime="2019-03-19T16:45:20+08:00">2019-03-19</time>
            

            
              

              
                
                <span class="post-meta-divider">|</span>
                

                <span class="post-meta-item-icon">
                  <i class="fa fa-calendar-check-o"></i>
                </span>
                
                  <span class="post-meta-item-text">更新于</span>
                
                <time title="修改时间：2019-04-11 21:50:09" itemprop="dateModified" datetime="2019-04-11T21:50:09+08:00">2019-04-11</time>
              
            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope="" itemtype="http://schema.org/Thing"><a href="/categories/HikariCP/" itemprop="url" rel="index"><span itemprop="name">HikariCP</span></a></span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        
          
            <p>说到数据库连接池，就不得不说到<code>Hikari</code>这位后起之秀，号称目前最快的数据库连接池，已成为<code>Spring Boot</code>默认的数据库连接池。</p>
<p>最近得空，想好好写一下之前对源码的总结，包括以前看源码的时候没有理解到位的地方再好好斟酌一下。</p>
<p>文本所采用的版本是当前最新版本 <a href="https://github.com/brettwooldridge/HikariCP/tree/HikariCP-3.3.1" target="_blank" rel="noopener">HikariCP-3.3.1</a>，尽量能够解读全面，也希望大家能反馈和理解表述错误或不合理的地方。</p>
<h4 id="核心并发管理"><a href="#核心并发管理" class="headerlink" title="核心并发管理"></a>核心并发管理</h4><p><code>ConcurrentBag</code>这个类可以说是 HikariCP 的最核心了，相当于<code>AbstractQueuedSynchronizer</code>之于<code>ReentrantLock</code>，它提供了对连接最基本的并发管理。</p>
<p>先来看看有哪些属性，搞清楚这些基本就知道作者是什么套路了，毕竟可以猜嘛！</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 共享列表，用于存储连接</span></span><br><span class="line"><span class="comment">// 连接池这种场景写少读多，使用 CopyOnWriteArrayList 并发性很好</span></span><br><span class="line"><span class="keyword">private</span> <span class="keyword">final</span> CopyOnWriteArrayList&lt;T&gt; sharedList;</span><br><span class="line"><span class="comment">// 标识是否使用弱引用</span></span><br><span class="line"><span class="keyword">private</span> <span class="keyword">final</span> <span class="keyword">boolean</span> weakThreadLocals;</span><br><span class="line"><span class="comment">// 线程列表，为了避免强烈的连接竞争，将连接缓存在线程内部</span></span><br><span class="line"><span class="keyword">private</span> <span class="keyword">final</span> ThreadLocal&lt;List&lt;Object&gt;&gt; threadList;</span><br><span class="line"><span class="comment">// 通知外部需要新增连接</span></span><br><span class="line"><span class="keyword">private</span> <span class="keyword">final</span> IBagStateListener listener;</span><br><span class="line"><span class="comment">// 等待数量</span></span><br><span class="line"><span class="keyword">private</span> <span class="keyword">final</span> AtomicInteger waiters;</span><br><span class="line"><span class="comment">// 标识是否已关闭</span></span><br><span class="line"><span class="keyword">private</span> <span class="keyword">volatile</span> <span class="keyword">boolean</span> closed;</span><br><span class="line"><span class="comment">// 传递连接的队列</span></span><br><span class="line"><span class="keyword">private</span> <span class="keyword">final</span> SynchronousQueue&lt;T&gt; handoffQueue;</span><br></pre></td></tr></table></figure>
<p>了解了基本属性，看看构造方法</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="title">ConcurrentBag</span><span class="params">(<span class="keyword">final</span> IBagStateListener listener)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="comment">// 监听器由外部传入</span></span><br><span class="line">   <span class="keyword">this</span>.listener = listener;</span><br><span class="line">   <span class="comment">// 当用户自定义了类加载时，该值为true，默认为false，也可以由用户指定</span></span><br><span class="line">   <span class="keyword">this</span>.weakThreadLocals = useWeakThreadLocals();</span><br><span class="line"></span><br><span class="line">   <span class="keyword">this</span>.handoffQueue = <span class="keyword">new</span> SynchronousQueue&lt;&gt;(<span class="keyword">true</span>);</span><br><span class="line">   <span class="keyword">this</span>.waiters = <span class="keyword">new</span> AtomicInteger();</span><br><span class="line">   <span class="keyword">this</span>.sharedList = <span class="keyword">new</span> CopyOnWriteArrayList&lt;&gt;();</span><br><span class="line">   <span class="keyword">if</span> (weakThreadLocals) &#123;</span><br><span class="line">      <span class="keyword">this</span>.threadList = ThreadLocal.withInitial(() -&gt; <span class="keyword">new</span> ArrayList&lt;&gt;(<span class="number">16</span>));</span><br><span class="line">   &#125;</span><br><span class="line">   <span class="keyword">else</span> &#123;</span><br><span class="line">       <span class="comment">// 作者自定义了 List，只实现了add、remove等几个必要的方法，源码比较简单，就不单独说了</span></span><br><span class="line">       <span class="comment">// 主要优化了添加元素时不进行 rangeCheck，移除元素时从后向前扫描</span></span><br><span class="line">      <span class="keyword">this</span>.threadList = ThreadLocal.withInitial(() -&gt; <span class="keyword">new</span> FastList&lt;&gt;(IConcurrentBagEntry.class, <span class="number">16</span>));</span><br><span class="line">   &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>管理的元素类型是 <code>IConcurrentBagEntry</code> 接口，ConcurrentBag 的内部接口，包含了4种状态，获取、设置以及 CAS 设置状态。<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">interface</span> <span class="title">IConcurrentBagEntry</span></span></span><br><span class="line"><span class="class"></span>&#123;</span><br><span class="line">  <span class="keyword">int</span> STATE_NOT_IN_USE = <span class="number">0</span>;</span><br><span class="line">  <span class="keyword">int</span> STATE_IN_USE = <span class="number">1</span>;</span><br><span class="line">  <span class="keyword">int</span> STATE_REMOVED = -<span class="number">1</span>;</span><br><span class="line">  <span class="keyword">int</span> STATE_RESERVED = -<span class="number">2</span>;</span><br><span class="line"></span><br><span class="line">  <span class="function"><span class="keyword">boolean</span> <span class="title">compareAndSet</span><span class="params">(<span class="keyword">int</span> expectState, <span class="keyword">int</span> newState)</span></span>;</span><br><span class="line">  <span class="function"><span class="keyword">void</span> <span class="title">setState</span><span class="params">(<span class="keyword">int</span> newState)</span></span>;</span><br><span class="line">  <span class="function"><span class="keyword">int</span> <span class="title">getState</span><span class="params">()</span></span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<h5 id="获取连接"><a href="#获取连接" class="headerlink" title="获取连接"></a>获取连接</h5><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> T <span class="title">borrow</span><span class="params">(<span class="keyword">long</span> timeout, <span class="keyword">final</span> TimeUnit timeUnit)</span> <span class="keyword">throws</span> InterruptedException</span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">   <span class="comment">// 首先从线程队列获取</span></span><br><span class="line">    <span class="keyword">final</span> List&lt;Object&gt; list = threadList.get();</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">int</span> i = list.size() - <span class="number">1</span>; i &gt;= <span class="number">0</span>; i--) &#123;</span><br><span class="line">        <span class="keyword">final</span> Object entry = list.remove(i);</span><br><span class="line">        <span class="meta">@SuppressWarnings</span>(<span class="string">"unchecked"</span>)</span><br><span class="line">        <span class="keyword">final</span> T bagEntry = weakThreadLocals ? ((WeakReference&lt;T&gt;) entry).get() : (T) entry;</span><br><span class="line">        <span class="comment">// 线程队列不为空则尝试 CAS 修改状态</span></span><br><span class="line">        <span class="keyword">if</span> (bagEntry != <span class="keyword">null</span> &amp;&amp; bagEntry.compareAndSet(STATE_NOT_IN_USE, STATE_IN_USE)) &#123;</span><br><span class="line">            <span class="comment">// 修改成功则表示抢占连接成功</span></span><br><span class="line">            <span class="keyword">return</span> bagEntry;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 代码走到这儿说明线程队列没有连接或所有连接都正在被使用，等待数量 +1</span></span><br><span class="line">    <span class="keyword">final</span> <span class="keyword">int</span> waiting = waiters.incrementAndGet();</span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">        <span class="comment">// 从共享队列获取</span></span><br><span class="line">        <span class="keyword">for</span> (T bagEntry : sharedList) &#123;</span><br><span class="line">            <span class="comment">// 老规矩，CAS 修改状态</span></span><br><span class="line">            <span class="keyword">if</span> (bagEntry.compareAndSet(STATE_NOT_IN_USE, STATE_IN_USE)) &#123;</span><br><span class="line">                <span class="comment">// 获取成功</span></span><br><span class="line">                <span class="keyword">if</span> (waiting &gt; <span class="number">1</span>) &#123;</span><br><span class="line">                    <span class="comment">// 获取成功但此时等待数量大于1，表示当前连接不够用，需要通知外部创建连接</span></span><br><span class="line">                    <span class="comment">// 为什么是大于 1，因为该线程在95行自增后，此时还没有 -1</span></span><br><span class="line">                    listener.addBagItem(waiting - <span class="number">1</span>);</span><br><span class="line">                &#125;</span><br><span class="line">                <span class="keyword">return</span> bagEntry;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        </span><br><span class="line">        <span class="comment">// 代码到这儿说明共享队列也没有空闲连接，通知外部创建连接</span></span><br><span class="line">        listener.addBagItem(waiting);</span><br><span class="line">        </span><br><span class="line">        timeout = timeUnit.toNanos(timeout);</span><br><span class="line">        <span class="keyword">do</span> &#123;</span><br><span class="line">            <span class="keyword">final</span> <span class="keyword">long</span> start = currentTime();</span><br><span class="line">            <span class="comment">// 阻塞等待连接释放或新增</span></span><br><span class="line">            <span class="keyword">final</span> T bagEntry = handoffQueue.poll(timeout, NANOSECONDS);</span><br><span class="line">            <span class="comment">// CAS 抢占</span></span><br><span class="line">            <span class="comment">// 为什么需要 CAS 抢占状态而不是直接使用？</span></span><br><span class="line">            <span class="comment">// 因为添加连接的时候会先把连接放到共享队列，再放到handoffQueue，放到共享队列时有可能刚好被其他线程抢占成功</span></span><br><span class="line">            <span class="keyword">if</span> (bagEntry == <span class="keyword">null</span> || bagEntry.compareAndSet(STATE_NOT_IN_USE, STATE_IN_USE)) &#123;</span><br><span class="line">                <span class="keyword">return</span> bagEntry;</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">            timeout -= elapsedNanos(start);</span><br><span class="line">        &#125; <span class="keyword">while</span> (timeout &gt; <span class="number">10_000</span>);</span><br><span class="line"></span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">finally</span> &#123;</span><br><span class="line">        <span class="comment">// 获取到连接了，等待数量 -1</span></span><br><span class="line">        waiters.decrementAndGet();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h5 id="释放连接到连接池"><a href="#释放连接到连接池" class="headerlink" title="释放连接到连接池"></a>释放连接到连接池</h5><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">requite</span><span class="params">(<span class="keyword">final</span> T bagEntry)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="comment">// 直接将状态设置为空闲状态</span></span><br><span class="line">    bagEntry.setState(STATE_NOT_IN_USE);</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 轮询等待数量 &gt; 0</span></span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; waiters.get() &gt; <span class="number">0</span>; i++) &#123;</span><br><span class="line">        <span class="comment">// 如果释放的连接还没有被其他线程占用，则检查handoffQueue是否有正在等待的线程</span></span><br><span class="line">        <span class="keyword">if</span> (bagEntry.getState() != STATE_NOT_IN_USE || handoffQueue.offer(bagEntry)) &#123;</span><br><span class="line">            <span class="keyword">return</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">// 每轮询256次，阻塞 10 微妙</span></span><br><span class="line">        <span class="keyword">else</span> <span class="keyword">if</span> ((i &amp; <span class="number">0xff</span>) == <span class="number">0xff</span>) &#123;</span><br><span class="line">            parkNanos(MICROSECONDS.toNanos(<span class="number">10</span>));</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">else</span> &#123;</span><br><span class="line">            <span class="comment">// 放弃时间片</span></span><br><span class="line">            yield();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">final</span> List&lt;Object&gt; threadLocalList = threadList.get();</span><br><span class="line">    <span class="keyword">if</span> (threadLocalList.size() &lt; <span class="number">50</span>) &#123;</span><br><span class="line">        <span class="comment">// 放到线程本地队列</span></span><br><span class="line">        threadLocalList.add(weakThreadLocals ? <span class="keyword">new</span> WeakReference&lt;&gt;(bagEntry) : bagEntry);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>一开始我也不明白作者为什么要每轮询 256 次阻塞 10 微妙（152-154），去 <code>issues</code> 搜索看到了<a href="https://github.com/brettwooldridge/HikariCP/issues/1305" target="_blank" rel="noopener">这个issue</a>，里面有这样一句话</p>
<blockquote>
<p>As there can be many threads in requite(), the occasional call to parkNanos() prevents CPU usage across many cores</p>
</blockquote>
<p>大意是：<code>requite()</code>这个方法有多个线程会调用，偶尔阻塞会防止 CPU 多个核心一直在这个方法轮转。</p>
<p>在并发比较大的情况下，有可能同时有多个线程释放连接，而获取连接的线程一直未得到调度，<code>yield()</code> 方法只是放弃时间片，线程进入就绪状态，有可能再次被调度。</p>
<h5 id="添加连接"><a href="#添加连接" class="headerlink" title="添加连接"></a>添加连接</h5><p>获取和释放连接的套路基本都清楚了，接下来看添加连接的操作吧，过程比获取和释放简单多了</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">add</span><span class="params">(<span class="keyword">final</span> T bagEntry)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">  <span class="keyword">if</span> (closed) &#123;</span><br><span class="line">     LOGGER.info(<span class="string">"ConcurrentBag has been closed, ignoring add()"</span>);</span><br><span class="line">     <span class="keyword">throw</span> <span class="keyword">new</span> IllegalStateException(<span class="string">"ConcurrentBag has been closed, ignoring add()"</span>);</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="comment">// 放到共享队列</span></span><br><span class="line">  sharedList.add(bagEntry);</span><br><span class="line"></span><br><span class="line">  <span class="comment">// 当等待线程数量 &gt; 0 就自旋通知等待线程获取连接</span></span><br><span class="line">  <span class="keyword">while</span> (waiters.get() &gt; <span class="number">0</span> &amp;&amp; bagEntry.getState() == STATE_NOT_IN_USE &amp;&amp; !handoffQueue.offer(bagEntry)) &#123;</span><br><span class="line">     yield();</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h5 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h5><p><code>Hikari</code> 的并发控制没有采取简单的加锁方式，而是采用 CAS 来实现线程间的资源竞争，减少了加锁的开销，用 <code>ThreadLocal</code> 缓存连接，最大限度的避免线程间的竞争 。</p>

          
        
      
    </div>

    

    
    
    

    

    
      
    
    

    

    <footer class="post-footer">
      

      

      

      
      
        <div class="post-eof"></div>
      
    </footer>
  </div>
  
  
  
  </article>


    
      

  

  
  
  

  

  <article class="post post-type-normal" itemscope="" itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/2018/06/24/Spring MVC如何处理RequestMapping方法中的请求参数/">

    <span hidden itemprop="author" itemscope="" itemtype="http://schema.org/Person">
      <meta itemprop="name" content="isunimp">
      <meta itemprop="description" content="涉猎广泛，不亦乐乎，不求甚解。">
      <meta itemprop="image" content="/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope="" itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="isunimp">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
                
                
                <a href="/2018/06/24/Spring MVC如何处理RequestMapping方法中的请求参数/" class="post-title-link" itemprop="http://yoursite.com/index.html">Spring MVC如何处理RequestMapping方法中的请求参数</a>
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">

            
            
            

            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              

              
                
              

              <time title="创建时间：2018-06-24 10:18:20" itemprop="dateCreated datePublished" datetime="2018-06-24T10:18:20+08:00">2018-06-24</time>
            

            
              

              
                
                <span class="post-meta-divider">|</span>
                

                <span class="post-meta-item-icon">
                  <i class="fa fa-calendar-check-o"></i>
                </span>
                
                  <span class="post-meta-item-text">更新于</span>
                
                <time title="修改时间：2019-03-18 20:10:34" itemprop="dateModified" datetime="2019-03-18T20:10:34+08:00">2019-03-18</time>
              
            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope="" itemtype="http://schema.org/Thing"><a href="/categories/Spring/" itemprop="url" rel="index"><span itemprop="name">Spring</span></a></span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        
          
            <p>Spring MVC是主流的MVC框架之一，可以无侵入的和Spring集成，使用起来极为方便，使用<code>@PathVariable</code> <code>@RequestBody</code>等注解自动帮我们处理请求参数，极大的减少了开发者的工作量，本文通过源码分析Spring MVC是如何处理这些注解的。</p>
<p>Spring MVC通过<code>DispatcherServlet</code>接到请求后，经过一系列的处理后（该过程不在本文讨论范围，故不在叙述，具体可自行Google，或参考<a href="https://segmentfault.com/a/1190000013816079" target="_blank" rel="noopener">Spring MVC流程解析</a>），找到该请求对应的Controller以及方法后，将这次方法的调用封装成一个<a href="https://github.com/spring-projects/spring-framework/blob/v5.1.2.RELEASE/spring-web/src/main/java/org/springframework/web/method/HandlerMethod.java" target="_blank" rel="noopener">HandlerMethod</a>对象。</p>
<h4 id="参数处理过程"><a href="#参数处理过程" class="headerlink" title="参数处理过程"></a>参数处理过程</h4><p><a href="https://github.com/spring-projects/spring-framework/blob/v5.1.2.RELEASE/spring-web/src/main/java/org/springframework/web/method/support/InvocableHandlerMethod.java#L151-L185" target="_blank" rel="noopener">getMethodArgumentValues</a>就是处理方法参数的核心代码（我是通过打断点一步步找到的0.0）<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// org.springframework.web.method.support.InvocableHandlerMethod </span></span><br><span class="line"><span class="keyword">private</span> Object[] getMethodArgumentValues(NativeWebRequest request, <span class="meta">@Nullable</span> ModelAndViewContainer mavContainer, Object... providedArgs) <span class="keyword">throws</span> Exception &#123;</span><br><span class="line">    <span class="comment">// InvocableHandlerMethod继承自HandlerMethod</span></span><br><span class="line">    <span class="comment">// 获取方法的所有参数</span></span><br><span class="line">    MethodParameter[] parameters = <span class="keyword">this</span>.getMethodParameters();</span><br><span class="line">    Object[] args = <span class="keyword">new</span> Object[parameters.length];</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 遍历处理所有参数</span></span><br><span class="line">    <span class="keyword">for</span>(<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; parameters.length; ++i) &#123;</span><br><span class="line">        MethodParameter parameter = parameters[i];</span><br><span class="line">        parameter.initParameterNameDiscovery(<span class="keyword">this</span>.parameterNameDiscoverer);</span><br><span class="line">        args[i] = <span class="keyword">this</span>.resolveProvidedArgument(parameter, providedArgs);</span><br><span class="line">        <span class="keyword">if</span> (args[i] == <span class="keyword">null</span>) &#123;</span><br><span class="line">            <span class="comment">// 根据方法名猜测是检查是否支持parameter的处理</span></span><br><span class="line">            <span class="comment">// 注意argumentResolvers</span></span><br><span class="line">            <span class="keyword">if</span> (<span class="keyword">this</span>.argumentResolvers.supportsParameter(parameter)) &#123;</span><br><span class="line">                <span class="keyword">try</span> &#123;</span><br><span class="line">                    <span class="comment">// 处理参数 </span></span><br><span class="line">                    args[i] = <span class="keyword">this</span>.argumentResolvers.resolveArgument(parameter, mavContainer, request, <span class="keyword">this</span>.dataBinderFactory);</span><br><span class="line">                &#125; <span class="keyword">catch</span> (Exception var9) &#123;</span><br><span class="line">                    <span class="keyword">if</span> (<span class="keyword">this</span>.logger.isDebugEnabled()) &#123;</span><br><span class="line">                        <span class="keyword">this</span>.logger.debug(<span class="keyword">this</span>.getArgumentResolutionErrorMessage(<span class="string">"Failed to resolve"</span>, i), var9);</span><br><span class="line">                    &#125;</span><br><span class="line">                    <span class="keyword">throw</span> var9;</span><br><span class="line">                &#125;</span><br><span class="line">            &#125; <span class="keyword">else</span> <span class="keyword">if</span> (args[i] == <span class="keyword">null</span>) &#123;</span><br><span class="line">                <span class="keyword">throw</span> <span class="keyword">new</span> IllegalStateException(<span class="string">"Could not resolve method parameter at index "</span> + parameter.getParameterIndex() + <span class="string">" in "</span> + parameter.getExecutable().toGenericString() + <span class="string">": "</span> + <span class="keyword">this</span>.getArgumentResolutionErrorMessage(<span class="string">"No suitable resolver for"</span>, i));</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> args;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>到这里可以看出是由<a href="https://github.com/spring-projects/spring-framework/blob/v5.1.2.RELEASE/spring-web/src/main/java/org/springframework/web/method/support/InvocableHandlerMethod.java#L56" target="_blank" rel="noopener">argumentResolvers</a>间接提供了参数的处理，argumentResolvers是一个<a href="https://github.com/spring-projects/spring-framework/blob/v5.1.2.RELEASE/spring-web/src/main/java/org/springframework/web/method/support/HandlerMethodArgumentResolverComposite.java" target="_blank" rel="noopener">HandlerMethodArgumentResolverComposite</a>对象</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 最重要的一个属性</span></span><br><span class="line"><span class="comment">// 存储了所有参数处理器</span></span><br><span class="line"><span class="keyword">private</span> <span class="keyword">final</span> List&lt;HandlerMethodArgumentResolver&gt; argumentResolvers = <span class="keyword">new</span> LinkedList();</span><br><span class="line"></span><br><span class="line"><span class="comment">// 添加处理器</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> HandlerMethodArgumentResolverComposite <span class="title">addResolver</span><span class="params">(HandlerMethodArgumentResolver resolver)</span></span>&#123;</span><br><span class="line">    <span class="keyword">this</span>.argumentResolvers.add(resolver);</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">this</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 添加处理器</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> HandlerMethodArgumentResolverComposite <span class="title">addResolvers</span><span class="params">(@Nullable HandlerMethodArgumentResolver... resolvers)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (resolvers != <span class="keyword">null</span>) &#123;</span><br><span class="line">    <span class="keyword">for</span> (HandlerMethodArgumentResolver resolver : resolvers) &#123;</span><br><span class="line">    	<span class="keyword">this</span>.argumentResolvers.add(resolver);</span><br><span class="line">    	&#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">this</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 添加处理器</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> HandlerMethodArgumentResolverComposite <span class="title">addResolvers</span><span class="params">(@Nullable List&lt;? extends HandlerMethodArgumentResolver&gt; resolvers)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (resolvers != <span class="keyword">null</span>) &#123;</span><br><span class="line">	    <span class="keyword">for</span> (HandlerMethodArgumentResolver resolver : resolvers) &#123;</span><br><span class="line">    	    <span class="keyword">this</span>.argumentResolvers.add(resolver);</span><br><span class="line">    	&#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">this</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>这些处理器都是<a href="https://github.com/spring-projects/spring-framework/blob/v5.1.2.RELEASE/spring-web/src/main/java/org/springframework/web/method/support/HandlerMethodArgumentResolver.java" target="_blank" rel="noopener">HandlerMethodArgumentResolver</a>接口对象，</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">interface</span> <span class="title">HandlerMethodArgumentResolver</span> </span>&#123;</span><br><span class="line">    </span><br><span class="line">    <span class="comment">// 检查是否支持参数</span></span><br><span class="line">    <span class="function"><span class="keyword">boolean</span> <span class="title">supportsParameter</span><span class="params">(MethodParameter parameter)</span></span>;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 处理参数</span></span><br><span class="line">    <span class="meta">@Nullable</span></span><br><span class="line">    <span class="function">Object <span class="title">resolveArgument</span><span class="params">(MethodParameter parameter, @Nullable ModelAndViewContainer mavContainer,NativeWebRequest webRequest, @Nullable WebDataBinderFactory binderFactory)</span> <span class="keyword">throws</span> Exception</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>但<code>HandlerMethodArgumentResolverComposite</code>本身也实现了这个接口，所以前面的<code>getMethodArgumentValues</code>方法里面可以直接调用<code>supportsParameter</code>,<code>resolveArgument</code>。</p>
<p><code>HandlerMethodArgumentResolverComposite</code>对<code>HandlerMethodArgumentResolver</code>接口的实现如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">supportsParameter</span><span class="params">(MethodParameter parameter)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">this</span>.getArgumentResolver(parameter) != <span class="keyword">null</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">public</span> Object <span class="title">resolveArgument</span><span class="params">(MethodParameter parameter, @Nullable ModelAndViewContainer mavContainer, NativeWebRequest webRequest, @Nullable WebDataBinderFactory binderFactory)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">    <span class="comment">// 获取解析器</span></span><br><span class="line">    HandlerMethodArgumentResolver resolver = <span class="keyword">this</span>.getArgumentResolver(parameter);</span><br><span class="line">    <span class="keyword">if</span> (resolver == <span class="keyword">null</span>) &#123;</span><br><span class="line">        <span class="keyword">throw</span> <span class="keyword">new</span> IllegalArgumentException(<span class="string">"Unknown parameter type ["</span> + parameter.getParameterType().getName() + <span class="string">"]"</span>);</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        <span class="comment">// 解析参数</span></span><br><span class="line">        <span class="keyword">return</span> resolver.resolveArgument(parameter, mavContainer, webRequest, binderFactory);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> *  获取对应的解析器</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="function"><span class="keyword">private</span> HandlerMethodArgumentResolver <span class="title">getArgumentResolver</span><span class="params">(MethodParameter parameter)</span> </span>&#123;</span><br><span class="line">    <span class="comment">// 从缓存中获取</span></span><br><span class="line">    HandlerMethodArgumentResolver result = (HandlerMethodArgumentResolver)<span class="keyword">this</span>.argumentResolverCache.get(parameter);</span><br><span class="line">    <span class="keyword">if</span> (result == <span class="keyword">null</span>) &#123;</span><br><span class="line">        Iterator var3 = <span class="keyword">this</span>.argumentResolvers.iterator();</span><br><span class="line">        <span class="keyword">while</span>(var3.hasNext()) &#123;</span><br><span class="line">            <span class="comment">// 遍历所有处理器</span></span><br><span class="line">            HandlerMethodArgumentResolver methodArgumentResolver = (HandlerMethodArgumentResolver)var3.next();</span><br><span class="line">            <span class="keyword">if</span> (<span class="keyword">this</span>.logger.isTraceEnabled()) &#123;</span><br><span class="line">                <span class="keyword">this</span>.logger.trace(<span class="string">"Testing if argument resolver ["</span> + methodArgumentResolver + <span class="string">"] supports ["</span> + parameter.getGenericParameterType() + <span class="string">"]"</span>);</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">           <span class="keyword">if</span> (methodArgumentResolver.supportsParameter(parameter)) &#123;</span><br><span class="line">                result = methodArgumentResolver;</span><br><span class="line">                <span class="keyword">this</span>.argumentResolverCache.put(parameter, methodArgumentResolver);</span><br><span class="line">                <span class="keyword">break</span>;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> result;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h4 id="处理器的实现"><a href="#处理器的实现" class="headerlink" title="处理器的实现"></a>处理器的实现</h4><p>到这里处理过程已经基本清楚了，不明白的小伙伴跟着代码多看两遍。现在要弄清楚Spring MVC何时往<code>HandlerMethodArgumentResolverComposite</code>里添加这些处理器的。</p>
<p>Spring MVC为请求匹配Controller以及对应的方法有一个很重要的类<a href="https://github.com/spring-projects/spring-framework/blob/v5.1.2.RELEASE/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/RequestMappingHandlerAdapter.java" target="_blank" rel="noopener">RequestMappingHandlerAdapter</a>，该类实现了<code>InitializingBean</code>接口:</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// InitializingBean接口实现</span></span><br><span class="line"><span class="meta">@Override</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">afterPropertiesSet</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    <span class="keyword">this</span>.initControllerAdviceCache();</span><br><span class="line">    List handlers;</span><br><span class="line">    <span class="keyword">if</span> (<span class="keyword">this</span>.argumentResolvers == <span class="keyword">null</span>) &#123;</span><br><span class="line">        handlers = <span class="keyword">this</span>.getDefaultArgumentResolvers();</span><br><span class="line">        <span class="comment">// 看这里O.O</span></span><br><span class="line">        <span class="keyword">this</span>.argumentResolvers = (<span class="keyword">new</span> HandlerMethodArgumentResolverComposite()).addResolvers(handlers);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (<span class="keyword">this</span>.initBinderArgumentResolvers == <span class="keyword">null</span>) &#123;</span><br><span class="line">        handlers = <span class="keyword">this</span>.getDefaultInitBinderArgumentResolvers();</span><br><span class="line">        <span class="keyword">this</span>.initBinderArgumentResolvers = (<span class="keyword">new</span> HandlerMethodArgumentResolverComposite()).addResolvers(handlers);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (<span class="keyword">this</span>.returnValueHandlers == <span class="keyword">null</span>) &#123;</span><br><span class="line">        handlers = <span class="keyword">this</span>.getDefaultReturnValueHandlers();</span><br><span class="line">        <span class="keyword">this</span>.returnValueHandlers = (<span class="keyword">new</span> HandlerMethodReturnValueHandlerComposite()).addHandlers(handlers);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 自带了很多参数处理器</span></span><br><span class="line"><span class="function"><span class="keyword">private</span> List&lt;HandlerMethodArgumentResolver&gt; <span class="title">getDefaultArgumentResolvers</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    List&lt;HandlerMethodArgumentResolver&gt; resolvers = <span class="keyword">new</span> ArrayList();</span><br><span class="line">    resolvers.add(<span class="keyword">new</span> RequestParamMethodArgumentResolver(<span class="keyword">this</span>.getBeanFactory(), <span class="keyword">false</span>));</span><br><span class="line">    resolvers.add(<span class="keyword">new</span> RequestParamMapMethodArgumentResolver());</span><br><span class="line">    resolvers.add(<span class="keyword">new</span> PathVariableMethodArgumentResolver());</span><br><span class="line">    resolvers.add(<span class="keyword">new</span> PathVariableMapMethodArgumentResolver());</span><br><span class="line">    resolvers.add(<span class="keyword">new</span> MatrixVariableMethodArgumentResolver());</span><br><span class="line">    resolvers.add(<span class="keyword">new</span> MatrixVariableMapMethodArgumentResolver());</span><br><span class="line">    resolvers.add(<span class="keyword">new</span> ServletModelAttributeMethodProcessor(<span class="keyword">false</span>));</span><br><span class="line">    resolvers.add(<span class="keyword">new</span> RequestResponseBodyMethodProcessor(<span class="keyword">this</span>.getMessageConverters(), <span class="keyword">this</span>.requestResponseBodyAdvice));</span><br><span class="line">    resolvers.add(<span class="keyword">new</span> RequestPartMethodArgumentResolver(<span class="keyword">this</span>.getMessageConverters(), <span class="keyword">this</span>.requestResponseBodyAdvice));</span><br><span class="line">    resolvers.add(<span class="keyword">new</span> RequestHeaderMethodArgumentResolver(<span class="keyword">this</span>.getBeanFactory()));</span><br><span class="line">    resolvers.add(<span class="keyword">new</span> RequestHeaderMapMethodArgumentResolver());</span><br><span class="line">    resolvers.add(<span class="keyword">new</span> ServletCookieValueMethodArgumentResolver(<span class="keyword">this</span>.getBeanFactory()));</span><br><span class="line">    resolvers.add(<span class="keyword">new</span> ExpressionValueMethodArgumentResolver(<span class="keyword">this</span>.getBeanFactory()));</span><br><span class="line">    resolvers.add(<span class="keyword">new</span> SessionAttributeMethodArgumentResolver());</span><br><span class="line">    resolvers.add(<span class="keyword">new</span> RequestAttributeMethodArgumentResolver());</span><br><span class="line">    resolvers.add(<span class="keyword">new</span> ServletRequestMethodArgumentResolver());</span><br><span class="line">    resolvers.add(<span class="keyword">new</span> ServletResponseMethodArgumentResolver());</span><br><span class="line">    resolvers.add(<span class="keyword">new</span> HttpEntityMethodProcessor(<span class="keyword">this</span>.getMessageConverters(), <span class="keyword">this</span>.requestResponseBodyAdvice));</span><br><span class="line">    resolvers.add(<span class="keyword">new</span> RedirectAttributesMethodArgumentResolver());</span><br><span class="line">    resolvers.add(<span class="keyword">new</span> ModelMethodProcessor());</span><br><span class="line">    resolvers.add(<span class="keyword">new</span> MapMethodProcessor());</span><br><span class="line">    resolvers.add(<span class="keyword">new</span> ErrorsMethodArgumentResolver());</span><br><span class="line">    resolvers.add(<span class="keyword">new</span> SessionStatusMethodArgumentResolver());</span><br><span class="line">    resolvers.add(<span class="keyword">new</span> UriComponentsBuilderMethodArgumentResolver());</span><br><span class="line">    <span class="keyword">if</span> (<span class="keyword">this</span>.getCustomArgumentResolvers() != <span class="keyword">null</span>) &#123;</span><br><span class="line">        resolvers.addAll(<span class="keyword">this</span>.getCustomArgumentResolvers());</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    resolvers.add(<span class="keyword">new</span> RequestParamMethodArgumentResolver(<span class="keyword">this</span>.getBeanFactory(), <span class="keyword">true</span>));</span><br><span class="line">    resolvers.add(<span class="keyword">new</span> ServletModelAttributeMethodProcessor(<span class="keyword">true</span>));</span><br><span class="line">    <span class="keyword">return</span> resolvers;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>在程序启动创建这个Bean的时候创建了一批参数处理器，看一下<a href="https://github.com/spring-projects/spring-framework/blob/v5.1.2.RELEASE/spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/RequestResponseBodyMethodProcessor.java" target="_blank" rel="noopener">RequestResponseBodyMethodProcessor</a>的supportsParameter方法实现<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">supportsParameter</span><span class="params">(MethodParameter parameter)</span> </span>&#123;</span><br><span class="line">    <span class="comment">// 检查这个参数是否有RequestBody注解</span></span><br><span class="line">    <span class="keyword">return</span> parameter.hasParameterAnnotation(RequestBody.class);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>就是我们熟知的<code>@RequestBody</code>注解，有兴趣的可以去看一下<code>resolveArgument</code>方法实现的解析过程，以及其他解析器的实现。</p>
<h4 id="自定义参数处理器"><a href="#自定义参数处理器" class="headerlink" title="自定义参数处理器"></a>自定义参数处理器</h4><p>我们可以实现<code>HandlerMethodArgumentResolver</code>接口来自定义处理器，例如读取Cookie或者Header构造一些信息<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Override</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">supportsParameter</span><span class="params">(MethodParameter methodParameter)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (methodParameter.getParameterAnnotation(某注解.class) != <span class="keyword">null</span>) &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">false</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="meta">@Override</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> Object <span class="title">resolveArgument</span><span class="params">(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory)</span><span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">    HttpServletRequest request = (HttpServletRequest) nativeWebRequest.getNativeRequest();</span><br><span class="line">    Object obj = request.getHeader(<span class="string">"xxx_header"</span>);</span><br><span class="line">    <span class="comment">// do...</span></span><br><span class="line">    <span class="keyword">return</span> obj;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>（全文完）</p>

          
        
      
    </div>

    

    
    
    

    

    
      
    
    

    

    <footer class="post-footer">
      

      

      

      
      
        <div class="post-eof"></div>
      
    </footer>
  </div>
  
  
  
  </article>


    
  </section>

  


          </div>
          

        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      

      <div class="site-overview-wrap sidebar-panel sidebar-panel-active">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope="" itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image" src="/images/avatar.jpg" alt="isunimp">
            
              <p class="site-author-name" itemprop="name">isunimp</p>
              <p class="site-description motion-element" itemprop="description">涉猎广泛，不亦乐乎，不求甚解。</p>
          </div>

          
            <nav class="site-state motion-element">
              
                <div class="site-state-item site-state-posts">
                
                  <a href="/archives/">
                
                    <span class="site-state-item-count">3</span>
                    <span class="site-state-item-name">日志</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-categories">
                  <a href="/categories/index.html">
                    
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">2</span>
                    <span class="site-state-item-name">分类</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-tags">
                  <a href="/tags/index.html">
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">5</span>
                    <span class="site-state-item-name">标签</span>
                  </a>
                </div>
              
            </nav>
          

          

          
            <div class="links-of-author motion-element">
              
                <span class="links-of-author-item">
                  
                  
                    
                  
                  
                    
                  
                  <a href="https://github.com/isunimp" title="GitHub &rarr; https://github.com/isunimp" rel="noopener" target="_blank"><i class="fa fa-fw fa-github"></i>GitHub</a>
                </span>
              
                <span class="links-of-author-item">
                  
                  
                    
                  
                  
                    
                  
                  <a href="mailto:ansheck@163.com" title="E-Mail &rarr; mailto:ansheck@163.com" rel="noopener" target="_blank"><i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                </span>
              
            </div>
          

          

          
          

          
            
          
          

        </div>
      </div>

      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; 2017 – <span itemprop="copyrightYear">2019</span>
  <span class="with-love" id="animate">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">isunimp</span>

  

  
</div>


  <div class="powered-by">由 <a href="https://hexo.io" class="theme-link" rel="noopener" target="_blank">Hexo</a> 强力驱动 v3.8.0</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 – <a href="https://theme-next.org" class="theme-link" rel="noopener" target="_blank">NexT.Mist</a> v6.6.0</div>




        








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

    

    
  </div>

  

<script>
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>


























  
  
    <script src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  


  


  <script src="/js/src/utils.js?v=6.6.0"></script>

  <script src="/js/src/motion.js?v=6.6.0"></script>



  
  

  

  


  <script src="/js/src/bootstrap.js?v=6.6.0"></script>



  



  











  





  

  

  

  

  

  
  

  

  

  

  

  

  

</body>
</html>
